package com.seeyon.apps.ext.kingdee.json;


import com.seeyon.apps.ext.kingdee.util.ClassUtil;
import com.seeyon.apps.ext.kingdee.util.ObjectUtil;
import com.seeyon.apps.ext.kingdee.util.StringUtil;
import com.seeyon.ctp.util.DateUtil;

import java.io.IOException;
import java.io.Writer;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;

/*
Information:java: 有关详细信息, 请使用 -Xlint:unchecked 重新编译。
 */
public class JSONObject extends HashMap<String,Object> {

    final static public String FULL_ST_FORMAT = "yyyy-MM-dd HH:mm:ss";


    public static JSONObject parseObject(String str)
    {
        try {
            return new JSONObject(str);
        } catch (JSONException e) {
            e.printStackTrace();

        }
        return new JSONObject();
    }


    @Override
    public final JSONObject clone() {

        JSONObject cloneJson = new JSONObject();
        cloneJson.putAll(this);
        return cloneJson;
    }

    /**
     * JSONObject.NULL is equivalent to the value that JavaScript calls null,
     * whilst Java's null is equivalent to the value that JavaScript calls
     * undefined.
     */
    static final class Null {

        /**
         * There is only intended to be a single instance of the NULL object,
         * so the clone method returns itself.
         *
         * @return NULL.
         */
        @Override
        @SuppressWarnings("unchecked")
        protected final Object clone() {
            return this;
        }


        /**
         * A Null object is equal to the null value and to itself.
         *
         * @param object An object to testaio for nullness.
         * @return true if the object parameter is the JSONObject.NULL object
         * or null.
         */
        @Override
        @SuppressWarnings("unchecked")
        public boolean equals(Object object) {
            return object == null || object == this;
        }


        /**
         * Get the "null" string value.
         *
         * @return The string "null".
         */
        @SuppressWarnings("unchecked")
        public String toString() {
            return "null";
        }
    }



    /**
     * It is sometimes more convenient and less ambiguous to have a
     * <code>NULL</code> object than to use Java's <code>null</code> value.
     * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.
     * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
     */
    public static final Object NULL = new Null();


    /**
     * Construct an empty JSONObject.
     */
    public JSONObject() {

    }


    /**
     * Construct a JSONObject from a subset of another JSONObject.
     * An array of strings is used to identify the keys that should be copied.
     * Missing keys are ignored.
     *
     * @param jo    A JSONObject.
     * @param names An array of strings.
     * @throws JSONException If a value is a non-finite number or if a name is duplicated.
     */
    public JSONObject(JSONObject jo, String[] names) throws JSONException {
        for (String name : names) {
            putOnce(name, jo.get(name));
        }
    }


    /**
     * Construct a JSONObject from a JSONTokener.
     *
     * @param x A JSONTokener object containing the source string.
     * @throws JSONException If there is a syntax error in the source string
     *                       or a duplicated key.
     */
    public JSONObject(JSONTokener x) throws JSONException {
        char c;
        String key;

        if (x.nextClean() != '{') {
            throw x.syntaxError("A JSONObject text must begin with '{'");
        }
        for (; ; ) {
            c = x.nextClean();
            switch (c) {
                case 0:
                    throw x.syntaxError("A JSONObject text must end with '}'");
                case '}':
                    return;
                default:
                    x.back();
                    key = x.nextValue().toString();
            }

            /*
             * The key is followed by ':'. We will also tolerate '=' or '=>'.
             */

            c = x.nextClean();
            if (c != ':') {
                throw x.syntaxError("Expected a ':' after a key");
            }
            putOnce(key, x.nextValue());

            /*
             * Pairs are separated by ','. We will also tolerate ';'.
             */

            switch (x.nextClean()) {
                case ';':
                case ',':
                    if (x.nextClean() == '}') {
                        return;
                    }
                    x.back();
                    break;
                case '}':
                    return;
                default:
                    throw x.syntaxError("Expected a ',' or '}'");
            }
        }
    }


    /**
     * Construct a JSONObject from a super.
     *
     * @param map A map object that can be used to initialize the contents of
     *            the JSONObject.
     */
    public JSONObject(Map<String, Object> map) {
        super.putAll(map);
    }

    /**
     * Construct a JSONObject from a super.
     * <p/>
     * Note: Use this constructor when the map contains <key,bean>.
     *
     * @param map               - A map with Key-Bean data.
     * @param includeSuperClass - Tell whether to include the super class properties.
     */
    public JSONObject(Map<String, Object> map, boolean includeSuperClass) {
        if (map != null) {
            for (Map.Entry<String, Object> e : map.entrySet()) {
                if (ClassUtil.isStandardProperty(e.getValue().getClass()))
                {
                    super.put(e.getKey(), e.getValue());
                } else {
                    super.put(e.getKey(), new JSONObject(e.getValue(), includeSuperClass));
                }
            }
        }
    }


    /**
     * Construct a JSONObject from an Object using bean getters.
     * It reflects on all of the public methods of the object.
     * For each of the methods with no parameters and a name starting
     * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter,
     * the method is invoked, and a key and the value returned from the getter method
     * are put into the new JSONObject.
     * <p/>
     * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. If the second remaining
     * character is not upper case, then the first
     * character is converted to lower case.
     * <p/>
     * For example, if an object has a method named <code>"getName"</code>, and
     * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>,
     * then the JSONObject will contain <code>"name": "Larry Fine"</code>.
     *
     * @param bean An object that has getter methods that should be used
     *             to make a JSONObject.
     */
    public JSONObject(Object bean) {
        this(bean, true);
    }


    public JSONObject(Object bean, boolean includeSuperClass) {
        if (bean instanceof Map)
        {
            super.putAll((Map)bean);
            return;
        }
        Class lass = bean.getClass();
        Map<String, Object> notExposeMap = new HashMap<String, Object>();
        Map<String, String> nameMap = new HashMap<String, String>();
        Field[] fields = ClassUtil.getDeclaredFields(lass);
        for (Field field : fields) {
            NotExpose notExpose = field.getAnnotation(NotExpose.class);
            if (notExpose != null) {
                notExposeMap.put(field.getName().toLowerCase(), notExpose);
            }
            SerializedName serializedName = field.getAnnotation(SerializedName.class);
            if (serializedName != null) {
                nameMap.put(field.getName().toLowerCase(), serializedName.value());
            }
        }


        Method[] methods = ClassUtil.getDeclaredReturnMethods(lass);
        for (Method method : methods) {
            if (!Modifier.isPublic(method.getModifiers())) continue;
            if ("void".equals(method.getReturnType().toString())) continue;
            NotExpose notExpose = method.getAnnotation(NotExpose.class);
            if (notExpose != null) continue;
            try {
                String name = method.getName();
                if (!StringUtil.hasLength(name)) continue;
                String key = StringUtil.empty;
                if (name.startsWith("get")) {
                    key = name.substring(3);
                } else if (name.startsWith("is")) {
                    key = name.substring(2);
                }
                if (notExposeMap.containsKey(key.toLowerCase())) continue;

                if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) {
                    if (key.length() == 1) {
                        key = key.toLowerCase();
                    } else if (!Character.isUpperCase(key.charAt(1))) {
                        key = key.substring(0, 1).toLowerCase() + key.substring(1);
                    }
                    Object result = method.invoke(bean, (Object[]) null);
                    if (result instanceof java.sql.Timestamp) {
                        result = new Date(((java.sql.Timestamp) result).getTime());
                    }

                    String kName = nameMap.get(key.toLowerCase());
                    if (kName != null && kName.length() > 0) {
                        key = kName;
                    }
                    if (result == null) {
                        super.put(key, NULL);
                    } else if (result instanceof Date) {
                        super.put(key, DateUtil.getDate((Date) result, FULL_ST_FORMAT));
                    } else if (result.getClass().isArray() || result instanceof Collection) {
                        super.put(key, new JSONArray(result,true));
                    } else if (result instanceof Map) {
                        super.put(key, new JSONObject(result, includeSuperClass));
                    } else if (ClassUtil.isStandardProperty(result.getClass())) { //Primitives, String and Wrapper
                        super.put(key, result);
                    } else {
                        if (result.getClass().getPackage().getName().startsWith("java") || result.getClass().getClassLoader() == null) {
                            super.put(key, result.toString());
                        } else {
                            if (includeSuperClass) super.put(key, new JSONObject(result, false));
                            else super.put(key, result);
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }



    /**
     * Construct a JSONObject from an Object, using reflection to find the
     * public members. The resulting JSONObject's keys will be the strings
     * from the names array, and the values will be the field values associated
     * with those keys in the object. If a key is not found or not visible,
     * then it will not be copied into the new JSONObject.
     *
     * @param object An object that has fields that should be used to make a
     *               JSONObject.
     * @param names  An array of strings, the names of the fields to be obtained
     *               from the object.
     */
    public JSONObject(Object object, String names[]) {
        if (object instanceof Map)
        {
            Map map = (Map)object;
            for (String name : names) {
                try {
                    putOpt(name, map.get(name));
                } catch (Exception e) {
                  /* forget about it */
                }
            }
            return;
        }
        Class c = object.getClass();
        for (String name : names) {
            try {
                putOpt(name, c.getField(name).get(object));
            } catch (Exception e) {
                /* forget about it */
            }
        }
    }


    /**
     * Construct a JSONObject from a source JSON text string.
     * This is the most commonly used JSONObject constructor.
     *
     * @param source A string beginning
     *               with <code>{</code>&nbsp;<small>(left brace)</small> and ending
     *               with <code>}</code>&nbsp;<small>(right brace)</small>.
     * @throws JSONException If there is a syntax error in the source
     *                       string or a duplicated key.
     */
    public JSONObject(String source) throws JSONException {
        this(new JSONTokener(source));
    }


    /**
     * Accumulate values under a key. It is similar to the put method except
     * that if there is already an object stored under the key then a
     * JSONArray is stored under the key to hold all of the accumulated values.
     * If there is already a JSONArray, then the new value is appended to it.
     * In contrast, the put method replaces the previous value.
     *
     * @param key   A key string.
     * @param value An object to be accumulated under the key.
     * @return this.
     * @throws JSONException If the value is an invalid number
     *                       or if the key is null.
     */
    public JSONObject accumulate(String key, Object value) throws JSONException {
        testValidity(value);
        Object o = get(key);
        if (o == null) {
            super.put(key, value instanceof JSONArray ?
                    new JSONArray().put(value) :
                    value);
        } else if (o instanceof JSONArray) {
            ((JSONArray) o).put(value);
        } else {
            super.put(key, new JSONArray().put(o).put(value));
        }
        return this;
    }


    /**
     * Append values to the array under a key. If the key does not exist in the
     * JSONObject, then the key is put in the JSONObject with its value being a
     * JSONArray containing the value parameter. If the key was already
     * associated with a JSONArray, then the value parameter is appended to it.
     *
     * @param key   A key string.
     * @param value An object to be accumulated under the key.
     * @return this.
     * @throws JSONException If the key is null or if the current value
     *                       associated with the key is not a JSONArray.
     */
    public JSONObject append(String key, Object value) throws JSONException {
        testValidity(value);
        Object o = get(key);
        if (o == null) {
            super.put(key, new JSONArray().put(value));
        } else if (o instanceof JSONArray) {
            super.put(key, ((JSONArray) o).put(value));
        }
        return this;
    }


    /**
     * Produce a string from a double. The string "null" will be returned if
     * the number is not finite.
     *
     * @param d A double.
     * @return A String.
     */
    static public String doubleToString(double d) {
        if (Double.isInfinite(d) || Double.isNaN(d)) {
            return "null";
        }

        // Shave off trailing zeros and decimal point, if possible.
        String s = Double.toString(d);
        if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
            while (s.endsWith("0")) {
                s = s.substring(0, s.length() - 1);
            }
            if (s.endsWith(".")) {
                s = s.substring(0, s.length() - 1);
            }
        }
        return s;
    }


    /**
     * Get the boolean value associated with a key.
     *
     * @param key A key string.
     * @return The truth.
     * @throws JSONException if the value is not a Boolean or the String "true" or "false".
     */
    public boolean getBoolean(String key)  {
        return ObjectUtil.toBoolean(get(key));
    }


    /**
     * Get the int value associated with a key. If the number value is too
     * large for an int, it will be clipped.
     *
     * @param key A key string.
     * @return The integer value.
     * @throws JSONException if the key is not found or if the value cannot
     *                       be converted to an integer.
     */
    public int getInt(String key)  {
        return ObjectUtil.toInt(get(key));
    }


    /**
     * Increment a property of a JSONObject. If there is no such property,
     * create one with a value of 1. If there is such a property, and if it is
     * an Integer, Long, Double, or Float, then add one to it.
     *
     * @param key A key string.
     * @return this.
     * @throws JSONException If there is already a property with this name that is not an
     *                       Integer, Long, Double, or Float.
     */
    public JSONObject increment(String key) {
        Object value =get(key);
        if (value == null) {
            this.put(key, 1);
        } else if (value instanceof Short) {
            this.put(key, (Short) value + 1);
        } else if (value instanceof Integer) {
            this.put(key, (Integer) value + 1);
        } else if (value instanceof Long) {
            this.put(key, (Long) value + 1);
        } else if (value instanceof Double) {
            this.put(key, (Double) value + 1);
        } else if (value instanceof Float) {
            this.put(key, (Float) value + 1);
        }
        return this;
    }

    /**
     * Get the JSONArray value associated with a key.
     *
     * @param key A key string.
     * @return A JSONArray which is the value.
     * @throws JSONException if the key is not found or
     *                       if the value is not a JSONArray.
     */
    public JSONArray getJSONArray(String key) {
        Object o = get(key);
        if (o instanceof JSONArray) {
            return (JSONArray) o;
        }
        return null;
    }


    /**
     * Get the JSONObject value associated with a key.
     *
     * @param key A key string.
     * @return A JSONObject which is the value.
     * @throws JSONException if the key is not found or
     *                       if the value is not a JSONObject.
     */
    public JSONObject getJSONObject(String key)  {
        Object o = get(key);
        if (o instanceof JSONObject) {
            return (JSONObject) o;
        }
        return null;
    }


    /**
     * Get an array of field names from a JSONObject.
     *
     * @return An array of field names, or null if there are no names.
     */
    public static String[] getNames(JSONObject jo) {
        int length = jo.size();
        if (length == 0) {
            return null;
        }
        Iterator iterator = jo.keys();
        String[] names = new String[length];
        int i = 0;
        while (iterator.hasNext()) {
            names[i] = (String) iterator.next();
            i += 1;
        }
        return names;
    }

    /**
     * Get an array of field names from an Object.
     *
     * @return An array of field names, or null if there are no names.
     */
    public static String[] getNames(Object object) {
        if (object == null) {
            return null;
        }
        Class lass = object.getClass();
        Field[] fields = lass.getFields();
        int length = fields.length;
        if (length == 0) {
            return null;
        }
        String[] names = new String[length];
        for (int i = 0; i < length; i += 1) {
            names[i] = fields[i].getName();
        }
        return names;
    }


    /**
     * Get the string associated with a key.
     *
     * @param key A key string.
     * @return A string which is the value.
     * @throws JSONException if the key is not found.
     */
    public String getString(String key)  {
        Object o = get(key);
        return o == null || "undefined".equals(o) ? StringUtil.empty : o.toString();
    }


    /**
     * Determine if the JSONObject contains a specific key.
     *
     * @param key A key string.
     * @return true if the key exists in the JSONObject.
     */
    public boolean has(String key) {
        return super.containsKey(key);
    }


    /**
     * Determine if the value associated with the key is null or if there is
     * no value.
     *
     * @param key A key string.
     * @return true if there is no value associated with the key or if
     * the value is the JSONObject.NULL object.
     */
    public boolean isNull(String key) {
        return JSONObject.NULL.equals(get(key));
    }



    /**
     * Produce a JSONArray containing the names of the elements of this
     * JSONObject.
     *
     * @return A JSONArray containing the key strings, or null if the JSONObject
     * is empty.
     */
    public JSONArray names() {
        JSONArray ja = new JSONArray();
        Iterator keys = this.keys();
        while (keys.hasNext()) {
            ja.put(keys.next());
        }
        return ja.size() == 0 ? null : ja;
    }

    /**
     * Produce a string from a Number.
     *
     * @param n A Number
     * @return A String.
     * @throws JSONException If n is a non-finite number.
     */
    static public String numberToString(Number n)
            throws JSONException {
        if (n == null) {
            throw new JSONException("Null pointer");
        }
        testValidity(n);

// Shave off trailing zeros and decimal point, if possible.

        String s = n.toString();
        if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
            while (s.endsWith("0")) {
                s = s.substring(0, s.length() - 1);
            }
            if (s.endsWith(".")) {
                s = s.substring(0, s.length() - 1);
            }
        }
        return s;
    }


    /**
     * Get an optional boolean associated with a key.
     * It returns false if there is no such key, or if the value is not
     * Boolean.TRUE or the String "true".
     *
     * @param key A key string.
     * @return The truth.
     */
    public boolean optBoolean(String key) {
        return optBoolean(key, false);
    }


    /**
     * Get an optional boolean associated with a key.
     * It returns the defaultValue if there is no such key, or if it is not
     * a Boolean or the String "true" or "false" (case insensitive).
     *
     * @param key          A key string.
     * @param defaultValue The default.
     * @return The truth.
     */
    public boolean optBoolean(String key, boolean defaultValue) {
        try {
            return getBoolean(key);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public JSONObject put(String key, JSONArray value) {
        super.put(key, value);
        return this;
    }

    /**
     * Put a key/value pair in the JSONObject, where the value will be a
     * JSONArray which is produced from a Collection.
     *
     * @param key   A key string.
     * @param value A Collection value.
     * @return this.
     * @throws JSONException
     */
    public JSONObject put(String key, Collection value) throws JSONException {
        super.put(key, new JSONArray(value,true));
        return this;
    }


    /**
     * Get an optional double associated with a key,
     * or NaN if there is no such key or if its value is not a number.
     * If the value is a string, an attempt will be made to evaluate it as
     * a number.
     *
     * @param key A string which is the key.
     * @return An object which is the value.
     */
    public double optDouble(String key) {
        return optDouble(key, Double.NaN);
    }


    /**
     * Get an optional double associated with a key, or the
     * defaultValue if there is no such key or if its value is not a number.
     * If the value is a string, an attempt will be made to evaluate it as
     * a number.
     *
     * @param key          A key string.
     * @param defaultValue The default.
     * @return An object which is the value.
     */
    public double optDouble(String key, double defaultValue) {
        try {
            Object o = get(key);
            return o instanceof Number ? ((Number) o).doubleValue() : new Double((String) o);
        } catch (Exception e) {
            return defaultValue;
        }
    }


    /**
     * Get an optional int value associated with a key,
     * or zero if there is no such key or if the value is not a number.
     * If the value is a string, an attempt will be made to evaluate it as
     * a number.
     *
     * @param key A key string.
     * @return An object which is the value.
     */
    public int optInt(String key) {
        return optInt(key, 0);
    }


    /**
     * Get an optional int value associated with a key,
     * or the default if there is no such key or if the value is not a number.
     * If the value is a string, an attempt will be made to evaluate it as
     * a number.
     *
     * @param key          A key string.
     * @param defaultValue The default.
     * @return An object which is the value.
     */
    public int optInt(String key, int defaultValue) {
        try {
            return getInt(key);
        } catch (Exception e) {
            return defaultValue;
        }
    }
    /**
     * Get an optional JSONArray associated with a key.
     * It returns null if there is no such key, or if its value is not a
     * JSONArray.
     *
     * @param key A key string.
     * @return A JSONArray which is the value.
     */
    public JSONArray optJSONArray(String key) {
        Object o = get(key);
        return o instanceof JSONArray ? (JSONArray) o : null;
    }


    /**
     * Get an optional JSONObject associated with a key.
     * It returns null if there is no such key, or if its value is not a
     * JSONObject.
     *
     * @param key A key string.
     * @return A JSONObject which is the value.
     */
    public JSONObject optJSONObject(String key) {
        Object o = get(key);
        return o instanceof JSONObject ? (JSONObject) o : null;
    }



    /**
     * Get an optional string associated with a key.
     * It returns an empty string if there is no such key. If the value is not
     * a string and is not null, then it is coverted to a string.
     *
     * @param key A key string.
     * @return A string which is the value.
     */
    public String optString(String key) {
        return optString(key, "");
    }


    /**
     * Get an optional string associated with a key.
     * It returns the defaultValue if there is no such key.
     *
     * @param key          A key string.
     * @param defaultValue The default.
     * @return A string which is the value.
     */
    public String optString(String key, String defaultValue) {
        Object o = get(key);
        return o != null ? o.toString() : defaultValue;
    }


    /**
     * Put a key/boolean pair in the JSONObject.
     *
     * @param key   A key string.
     * @param value A boolean which is the value.
     * @return this.
     * @throws JSONException If the key is null.
     */
    public JSONObject put(String key, boolean value)  {
        super.put(key, value ? Boolean.TRUE : Boolean.FALSE);
        return this;
    }

    /**
     *
     * @param key   A key string.
     * @param value A Map value.
     * @return this.
     * @throws JSONException
     */
    public JSONObject put(String key, Map value)  {
        if (value instanceof JSONObject)
        {
            super.put(key, value);
        } else
            super.put(key, new JSONObject(value,true));
        return this;
    }


    /**
     * Put a key/value pair in the JSONObject. If the value is null,
     * then the key will be removed from the JSONObject if it is present.
     *
     * @param key   A key string.
     * @param value An object which is the value. It should be of one of these
     *              types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
     *              or the JSONObject.NULL object.
     * @return this.
     */
    public JSONObject put(String key, Object value)  {
        if (key == null) return this;
        if (value != null) {
            try {
                testValidity(value);
                super.put(key, value);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            super.remove(key);
        }
        return this;
    }


    /**
     * Put a key/value pair in the JSONObject, but only if the key and the
     * value are both non-null, and only if there is not already a member
     * with that name.
     *
     * @param key key
     * @param value 值
     * @return his.
     * @throws JSONException if the key is a duplicate
     */
    public JSONObject putOnce(String key, Object value) throws JSONException {
        if (key != null && value != null) {
            if (get(key) != null) {
                throw new JSONException("Duplicate key \"" + key + "\"");
            }
            super.put(key, value);
        }
        return this;
    }


    /**
     * Put a key/value pair in the JSONObject, but only if the
     * key and the value are both non-null.
     *
     * @param key   A key string.
     * @param value An object which is the value. It should be of one of these
     *              types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
     *              or the JSONObject.NULL object.
     * @return this.
     * @throws JSONException If the value is a non-finite number.
     */
    public JSONObject putOpt(String key, Object value) throws JSONException {
        if (key != null && value != null) {
            super.put(key, value);
        }
        return this;
    }

    /**
     * Remove a name and its value, if present.
     *
     * @param key The name to be removed.
     * @return The value that was associated with the name,
     * or null if there was no value.
     */
    public Object remove(String key) {
        return super.remove(key);
    }

    /**
     * Get an enumeration of the keys of the JSONObject.
     *
     * @return An iterator of the keys.
     */
    public Iterator keys() {
        return super.keySet().iterator();
    }

    public Map toMap() {
        Map<String,Object> map = new HashMap<String, Object>();
        for (String key:keySet())
        {
            map.put(key,get(key));
        }
        return map;
    }

    /**
     * Try to convert a string into a number, boolean, or null. If the string
     * can't be converted, return the string.
     *
     * @param s A String.
     * @return A simple JSON value.
     */
    static public Object stringToValue(String s) {
        if (s.equals("")) {
            return s;
        }
        if (s.equalsIgnoreCase("true")) {
            return Boolean.TRUE;
        }
        if (s.equalsIgnoreCase("false")) {
            return Boolean.FALSE;
        }
        if (s.equalsIgnoreCase("null")) {
            return JSONObject.NULL;
        }

        /*
        * If it might be a number, try converting it. We support the 0- and 0x-
        * conventions. If a number cannot be produced, then the value will just
        * be a string. Note that the 0-, 0x-, plus, and implied string
        * conventions are non-standard. A JSON parser is free to accept
        * non-JSON forms as long as it accepts all correct JSON forms.
        */

        char b = s.charAt(0);
        if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {
            if (b == '0') {
                if (s.length() > 2 &&
                        (s.charAt(1) == 'x' || s.charAt(1) == 'X')) {
                    try {
                        return Integer.parseInt(s.substring(2), 16);
                    } catch (Exception e) {
                        /* Ignore the error */
                    }
                } else {
                    try {
                        return Integer.parseInt(s, 8);
                    } catch (Exception e) {
                        /* Ignore the error */
                    }
                }
            }
            try {
                if (s.indexOf('.') > -1 || s.indexOf('e') > -1 || s.indexOf('E') > -1) {
                    return Double.valueOf(s);
                } else {
                    Long myLong = new Long(s);
                    if (myLong == myLong.intValue()) {
                        return myLong.intValue();
                    } else {
                        return myLong;
                    }
                }
            } catch (Exception f) {
                /* Ignore the error */
            }
        }
        return s;
    }


    /**
     * Throw an exception if the object is an NaN or infinite number.
     *
     * @param o The object to testaio.
     * @throws JSONException If o is a non-finite number.
     */
    static void testValidity(Object o) throws JSONException {
        if (o != null) {
            if (o instanceof Double) {
                if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
                    throw new JSONException("JSON does not allow non-finite numbers.");
                }
            } else if (o instanceof Float) {
                if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
                    throw new JSONException("JSON does not allow non-finite numbers.");
                }
            }
        }
    }


    /**
     * Produce a JSONArray containing the values of the members of this
     * JSONObject.
     *
     * @param names A JSONArray containing a list of key strings. This
     *              determines the sequence of the values in the result.
     * @return A JSONArray of values.
     * @throws JSONException If any of the values are non-finite numbers.
     */
    public JSONArray toJSONArray(JSONArray names) throws JSONException {
        if (names == null || names.size() == 0) {
            return null;
        }
        JSONArray ja = new JSONArray();
        for (int i = 0; i < names.size(); i += 1) {
            ja.put(get(names.getString(i)));
        }
        return ja;
    }

    /**
     * Make a JSON text of this JSONObject. For compactness, no whitespace
     * is added. If this would not result in a syntactically correct JSON text,
     * then null will be returned instead.
     * <p/>
     * Warning: This method assumes that the data structure is acyclical.
     *
     * @return a printable, displayable, portable, transmittable
     * representation of the object, beginning
     * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
     * with <code>}</code>&nbsp;<small>(right brace)</small>.
     */
    public String toString() {
        try {
            return toString(0, 0);
        } catch (Exception e) {

            return StringUtil.empty;
        }
    }

    public String toString(int indentFactor) {
        return toString(indentFactor, 0);
    }

    /**
     * Make a prettyprinted JSON text of this JSONObject.
     * <p/>
     * Warning: This method assumes that the data structure is acyclical.
     *
     * @param indentFactor The number of spaces to add to each level of
     *                     indentation.
     * @param indent       The indentation of the top level.
     * @return a printable, displayable, transmittable
     * representation of the object, beginning
     * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
     * with <code>}</code>&nbsp;<small>(right brace)</small>.
     */
    String toString(int indentFactor, int indent) {

        StringBuilder sb = new StringBuilder("{");
        try {
            int j;

            if (super.isEmpty()) {
                return "{}";
            }
            Iterator keys = super.keySet().iterator();
            Object o;
            if (super.size() == 1) {
                o = keys.next();
                sb.append(StringUtil.quote(o.toString(), true));
                sb.append(": ");
                sb.append(valueToString(super.get(o), indentFactor, indent));
            } else {
                int newIndent = indent + indentFactor;
                while (keys.hasNext()) {
                    o = keys.next();
                    if (sb.length() > 1) {
                        sb.append(",");
                        if (indentFactor > 0) sb.append('\n');
                    } else {
                        if (indentFactor > 0) sb.append('\n');
                    }
                    for (j = 0; j < newIndent; j += 1) {
                        sb.append(' ');
                    }
                    sb.append(StringUtil.quote(o.toString(), true));
                    sb.append(": ");
                    sb.append(valueToString(super.get(o), indentFactor, newIndent));
                }
                if (sb.length() > 1) {
                    if (indentFactor > 0) sb.append('\n');
                    for (j = 0; j < indent; j += 1) {
                        sb.append(' ');
                    }
                }
            }
        } catch (Exception f) {

            return "{}";
        }
        sb.append('}');

        return sb.toString();
    }


    /**
     * Make a JSON text of an Object value. If the object has an
     * value.toJSONString() method, then that method will be used to produce
     * the JSON text. The method is required to produce a strictly
     * conforming text. If the object does not contain a toJSONString
     * method (which is the most common case), then a text will be
     * produced by other means. If the value is an array or Collection,
     * then a JSONArray will be made from it and its toJSONString method
     * will be called. If the value is a MAP, then a JSONObject will be made
     * from it and its toJSONString method will be called. Otherwise, the
     * value's toString method will be called, and the result will be quoted.
     * <p/>
     * <p/>
     * Warning: This method assumes that the data structure is acyclical.
     *
     * @param value The value to be serialized.
     * @return a printable, displayable, transmittable
     * representation of the object, beginning
     * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
     * with <code>}</code>&nbsp;<small>(right brace)</small>.
     * @throws JSONException If the value is or contains an invalid number.
     */
    static String valueToString(Object value) throws JSONException {
        return valueToString(value, 0, 0);
    }


    /**
     * Make a prettyprinted JSON text of an object value.
     * <p/>
     * Warning: This method assumes that the data structure is acyclical.
     *
     * @param value        The value to be serialized.
     * @param indentFactor The number of spaces to add to each level of
     *                     indentation.
     * @param indent       The indentation of the top level.
     * @return a printable, displayable, transmittable
     * representation of the object, beginning
     * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
     * with <code>}</code>&nbsp;<small>(right brace)</small>.
     * @throws JSONException If the object contains an invalid number.
     */
    static String valueToString(Object value, int indentFactor, int indent) throws JSONException {
        if (value == null) return "null";
        if (value instanceof String) {
            if (((String) value).startsWith("<script>") && ((String) value).endsWith("</script>")) {
                return StringUtil.substringOutBetween(value.toString(), "<script>", "</script>");
            } else
                return StringUtil.quote(value.toString(), true);
        }

        if (value instanceof Date) {
            return StringUtil.quote(DateUtil.getDate((Date) value, FULL_ST_FORMAT), true);
        }

        if (value instanceof Boolean) {
            return value.toString();
        }

        if (value instanceof Number) {
            return numberToString((Number) value);
        }

        if (value instanceof JSONString) {
            return ((JSONString) value).toJSONString();
        }

        if (value instanceof JSONArray) {

            return ((JSONArray) value).toString(indentFactor, indent);
        }
        if (value instanceof JSONObject) {
            return ((JSONObject) value).toString(indentFactor, indent);
        }

        if (value instanceof Map) {
            return new JSONObject((Map) value).toString(indentFactor, indent);
        }

        if (value instanceof Collection || value instanceof Iterable || value.getClass().isArray()) {
            return new JSONArray(value).toString(indentFactor, indent);
        }
        if (value instanceof Serializable && !ClassUtil.isStandardProperty(value.getClass())) {
            return new JSONObject(value).toString(indentFactor, indent);
        }
        return StringUtil.quote(value.toString(), true);
    }


    /**
     * Write the contents of the JSONObject as JSON text to a writer.
     * For compactness, no whitespace is added.
     * <p/>
     * Warning: This method assumes that the data structure is acyclical.
     *
     * @return The writer.
     * @throws JSONException
     */
    public Writer write(Writer writer) throws JSONException {
        try {
            boolean b = false;
            Iterator keys = super.keySet().iterator();
            writer.write('{');
            while (keys.hasNext()) {
                if (b) {
                    writer.write(',');
                }
                Object k = keys.next();
                writer.write(StringUtil.quote(k.toString(), true));
                writer.write(':');
                Object v = super.get(k);
                writer.write(valueToString(v));
                b = true;
            }
            writer.write('}');
            return writer;
        } catch (IOException e) {
            throw new JSONException(e);
        }
    }
}